package com.tc.vms;

import com.tc.vms.iface.VmsServiceAdaptor;
import com.tc.vms.consumer.QueueMetaData;
import com.tc.vms.exception.VmsClientErrorCode;
import com.tc.vms.exception.VmsClientException;
import com.tc.vms.iface.IContext;
import com.tc.vms.iface.VmsServiceAdaptor;
import com.tc.vms.producer.ChannelMetaData;

import static com.tc.vms.config.VmsClientContext.VmsClientContextBuilder;

/**
 * Created by yonghua.zhang on 2016/2/18.
 */
public class VmsMetaDataReader extends VmsServiceAdaptor {
    private VmsBootstrap bootstrap;
    private final VmsClientContextBuilder builder = new VmsClientContextBuilder();

    public VmsMetaDataReader() {
    }

    public VmsClientContextBuilder config() {
        return this.builder;
    }

    public ChannelMetaData getChannelMetaData(String channelName) throws VmsClientException {
        if (!isOpen)
            throw new VmsClientException("VmsMetaDataReader not be init.", VmsClientErrorCode.VMS_SYS_ERR_NOT_RUNNING);
        try {
            return bootstrap.getVmsRouterManager().readChannelMetaData(channelName, null);
        } catch (Exception e) {
            throw new VmsClientException("getChannelMetaData error." + e.getMessage());
        }
    }

    public QueueMetaData getQueueMetaData(String queueName) throws VmsClientException {
        if (!isOpen)
            throw new VmsClientException("VmsMetaDataReader not be init.", VmsClientErrorCode.VMS_SYS_ERR_NOT_RUNNING);
        try {
            return bootstrap.getVmsRouterManager().readQueueMetaData(queueName, null);
        } catch (Exception e) {
            throw new VmsClientException("getQueueMetaData error." + e.getMessage());
        }
    }

    @Override
    public boolean init(IContext context) throws VmsClientException {
        if (!isOpen) {
            bootstrap = new VmsBootstrap(builder.build());
            bootstrap.init(context);
            isOpen = true;
        }
        return isOpen;
    }

    @Override
    public boolean start() throws VmsClientException {
        return init(null);
    }

    @Override
    public void shutdown() {
        if (isOpen) {
            isOpen = false;
            bootstrap.shutdown();
            bootstrap = null;
        }
    }
}
